package com.cloud.observer;




import com.cloud.observer.handler.IExecuteHandler;
import com.cloud.observer.handler.successHandler.ISuccessHandler;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: create by God of SJF
 * @version: v1.0
 * @description: com.cloud.observer
 * @date:2021/1/12
 */
public class ScheduledObserverPool implements Runnable {

    ScheduledInfo scheduledInfo;

    BaseScheduledObserver baseScheduledObserver;

    public ScheduledObserverPool(ScheduledInfo scheduledInfo, BaseScheduledObserver baseScheduledObserver) {
        this.scheduledInfo = scheduledInfo;
        this.baseScheduledObserver = baseScheduledObserver;
    }

    @Override
    public void run() {
        synchronized (scheduledInfo) {
            if(scheduledInfo.getInit() == 1){
                return;
            }
            if (scheduledInfo.getErrorSet().contains(scheduledInfo.getEdition())) {
                return;
            }

            scheduledInfo.getErrorSet().add(scheduledInfo.getEdition());
            if(scheduledInfo.getSuccessSend()){
                List<ISuccessHandler> successHandlerList = scheduledInfo.getSuccessHandlerList();
                for(ISuccessHandler handler : successHandlerList) {
                    handler.success();
                }
            }
            if (scheduledInfo.getErrorSend()) {
                Integer delayNum = scheduledInfo.getDelayNum();
                Integer delayNumLimit = scheduledInfo.getDelayNumLimit();
                Integer delayLimitTime = scheduledInfo.getDelayLimitTime();
                Date lastBegin = scheduledInfo.getLastBegin();//上次执行开始时间
                Date lastEnd = scheduledInfo.getLastEnd();//上次执行结束时间
                TimeUnit timeUnit = scheduledInfo.getTimeUnit();//执行单位
                Long gap = lastEnd.getTime() - lastBegin.getTime();
                if (timeUnit == TimeUnit.SECONDS) {
                    Long thisGap = gap / 1000;
                    Integer tr = thisGap.intValue();
                    if (tr >= delayLimitTime) {
                        delayNum++;
                    }
                    if (delayNum >= delayNumLimit) {
                        List<IExecuteHandler> errorHandlerList = scheduledInfo.getExecuteHandlerList();
                        if (!errorHandlerList.isEmpty()) {
                            for (IExecuteHandler handler : errorHandlerList) {
                                handler.handle();
                                handler.send();
                            }
                        }
                        delayNum = 0;
                        scheduledInfo.setDelayNum(delayNum);
                        baseScheduledObserver.map.put(scheduledInfo.name, scheduledInfo);
                    }
                }
            }
        }
    }
}
